"""Fix LDAP password encryption

Revision ID: 50c8360d9616
Revises: dc143ce20fcd
Create Date: 2021-03-31 09:08:41.264829+00:00

"""
from alembic import op
import sqlalchemy as sa

from middlewared.plugins.pwenc import encrypt, decrypt


# revision identifiers, used by Alembic.
revision = '50c8360d9616'
down_revision = 'dc143ce20fcd'
branch_labels = None
depends_on = None


def upgrade():
    conn = op.get_bind()
    for row in conn.execute("SELECT * FROM directoryservice_ldap").fetchall():
        if row["ldap_binddn"] and decrypt(row["ldap_binddn"]):
            # New (>= 12.0) configurations have ldap_binddn erroneously encrypted instead of ldap_bindpw
            # due to fd623d849d1abee8c5786128b150e92209ba1f69
            conn.execute("UPDATE directoryservice_ldap SET ldap_binddn = ?, ldap_bindpw = ? WHERE id = ?", [
                decrypt(row["ldap_binddn"]),
                encrypt(row["ldap_bindpw"]),
                row["id"],
            ])

    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###
